package com.community.common.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.community.common.config.BizException;
import com.community.common.mapper.BuildingMapper;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.domain.Building;
import com.community.common.pojo.dto.BuildingPageQueryDto;
import com.community.common.pojo.response.MyResponse;
import com.community.common.util.CommonUtil;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 小区表 服务实现类
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@Slf4j
@Service
public class BuildingService {

    @Resource
    private BuildingMapper buildingMapper;

    public MyResponse add(Building building) {
        if (ObjectUtils.isEmpty(building) || StringUtils.isAnyBlank(building.getXqId(), building.getLdh())) {
            throw new BizException("输入参数不能为空");
        }
        building.setId(CommonUtil.getIdStr());
        int insert = buildingMapper.insert(building);
        if (insert == 1) {
            return MyResponse.success();
        }
        return MyResponse.fail();
    }

    public List<String> getLdIdListByXqId(String xqId) {
        LambdaQueryWrapper<Building> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Building::getXqId, xqId);
        List<Building> buildingList = buildingMapper.selectList(wrapper);
        List<String> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(buildingList)) {
            return list;
        }
        return buildingList.stream().map(Building::getId).collect(Collectors.toList());
    }

    public List<Building> pageQuery(PageRequest<BuildingPageQueryDto> pageQueryDto) {
        BuildingPageQueryDto buildingPageQueryDto = pageQueryDto.getCondition();
        LambdaQueryWrapper<Building> wrapper = new LambdaQueryWrapper<>();
        if (!Objects.isNull(buildingPageQueryDto)) {
            if (StringUtils.isNotBlank(buildingPageQueryDto.getXqId())) {
                wrapper.eq(Building::getXqId, buildingPageQueryDto.getXqId());
            }
        }
        PageHelper.startPage(pageQueryDto.getCurrentPage(), pageQueryDto.getPageSize());
        return buildingMapper.selectList(wrapper);
    }

}